#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "../network/networkclient.h"
#include <QMessageBox>
#include <QCryptographicHash>
#include <QDebug>
#include <QJsonDocument>
#include <QDateTime>

RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);
    
    setWindowTitle("用户注册");
    
    // ComboBox默认选择第一项（患者、男）
    
    // 连接网络信号
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &RegisterDialog::onMessageReceived);
}

RegisterDialog::~RegisterDialog() {
    delete ui;
}

void RegisterDialog::on_registerButton_clicked() {
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();
    QString realName = ui->realNameEdit->text().trimmed();
    QString contact = ui->contactEdit->text().trimmed();
    
    // 验证输入
    if (username.isEmpty() || password.isEmpty() || realName.isEmpty() || contact.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写所有必填项");
        return;
    }
    
    if (password.length() < 6) {
        QMessageBox::warning(this, "提示", "密码长度至少6位");
        return;
    }
    
    // 检查服务器连接
    if (!NetworkClient::instance().isConnected()) {
        QString host = NetworkClient::instance().defaultHost();
        quint16 port = NetworkClient::instance().defaultPort();
        if (!NetworkClient::instance().connectToServer(host, port)) {
            QMessageBox::critical(this, "连接失败", 
                QString("无法连接到服务器 %1:%2\n请确保服务器已启动").arg(host).arg(port));
            return;
        }
    }
    
    // 获取用户选择的类型 (0=患者, 1=医生)
    int userType = (ui->userTypeComboBox->currentIndex() == 1) ? 2 : 1;
    
    // 生成临时身份证号（避免重复）
    QString tempIdCard = QString("TEMP%1%2").arg(userType).arg(QDateTime::currentMSecsSinceEpoch());
    
    // 加密密码
    QString hashedPassword = QString(QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Sha256).toHex());
    
    // 构建注册请求
    QJsonObject request;
    request["username"] = username;
    request["password"] = hashedPassword;
    request["real_name"] = realName;
    request["id_card"] = tempIdCard; // 使用临时身份证号
    request["phone"] = contact;
    request["role"] = userType;
    
    // 添加性别
    QString gender = ui->genderComboBox->currentText();
    request["gender"] = gender;
    request["address"] = "";
    
    qDebug() << "发送注册请求:" << request;
    NetworkClient::instance().sendRequest(MSG_REGISTER, request);
    
    // 禁用按钮，防止重复提交
    ui->registerButton->setEnabled(false);
    ui->registerButton->setText("注册中...");
}

void RegisterDialog::on_cancelButton_clicked() {
    reject();
}

void RegisterDialog::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_REGISTER_RESPONSE) {
        qDebug() << "收到注册响应:" << data;
        
        // 恢复按钮状态
        ui->registerButton->setEnabled(true);
        ui->registerButton->setText("注 册");
        
        bool success = data["success"].toBool();
        QString message = data["message"].toString();
        
        // 如果消息为空，使用默认信息
        if (message.isEmpty()) {
            message = success ? "注册成功" : "注册失败，请检查输入信息";
        }
        
        if (success) {
            QMessageBox::information(this, "成功", message);
            accept();
        } else {
            // 显示完整的错误信息
            QString errorMsg = message;
            if (data.contains("error")) {
                errorMsg = data["error"].toString();
            }
            QMessageBox::warning(this, "注册失败", 
                QString("注册失败！\n\n错误信息：%1\n\n完整响应：%2")
                .arg(errorMsg)
                .arg(QString(QJsonDocument(data).toJson())));
        }
    }
}

